package com.corpgovernment.organization.service;

import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.CommonException;
import com.corpgovernment.redis.cache.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.corpgovernment.api.basic.metadata.ELoginStatus.USERNAME_OR_PWD_ERROR;

/**
 * @author jhxue
 * @create 2022-01-06-16:28
 */
@Service
public class LoginHelpService {

	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private OrganizationApollo organizationApollo;
	/**
	 * 密码错误次数缓存
	 */
	private static final String RETRY_COUNT_PREFIX = "retry_count_";

	/**
	 * 登录失败处理
	 *
	 * @param accountName
	 */
	public void doFailure(String accountName) {
		int retryCount = this.getRetryCount(accountName);
		// 最大错误次数
		int maxLoginCount = organizationApollo.getMaxLoginCount();
		int current = retryCount + 1;
		this.setRetryCount(accountName, current);
		if (current > maxLoginCount) {
			throw new CommonException(USERNAME_OR_PWD_ERROR.getValue(), "您的用户名或密码错误次数已满，将锁定10分钟。");
		}
		int remain = maxLoginCount - current;
		if (remain == 0) {
			throw new CommonException(USERNAME_OR_PWD_ERROR.getValue(), "您的用户名或密码错误次数已满，将锁定10分钟。");
		} else {
			throw new CommonException(USERNAME_OR_PWD_ERROR.getValue(), "您的用户名或密码错误，还有" + remain + "次机会。");
		}
	}

	/**
	 * 登录成功处理
	 *
	 * @param accountName
	 */
	public void doSuccess(String accountName) {
		this.clearRetryCount(accountName);
	}

	/**
	 * 设置失败次数
	 *
	 * @param accountName
	 * @param current
	 */
	private void setRetryCount(String accountName, int current) {
		redisUtils.setCache(RETRY_COUNT_PREFIX + accountName, current, 600);
	}

	/**
	 * 清除登录失败缓存
	 *
	 * @param accountName
	 */
	private void clearRetryCount(String accountName) {
		redisUtils.delete(RETRY_COUNT_PREFIX + accountName);
	}

	/**
	 * 获取当前账号登录失败次数
	 *
	 * @param accountName
	 * @return
	 */
	private int getRetryCount(String accountName) {
		Integer value = redisUtils.getCache(RETRY_COUNT_PREFIX + accountName, Integer.class);
		if (value == null) {
			return 0;
		}
		return value;
	}

	/**
	 * 登录check
	 *
	 * @param accountName
	 */
	public void doCheck(String accountName) {
		int retryCount = this.getRetryCount(accountName);
		// 最大错误次数
		int maxLoginCount = organizationApollo.getMaxLoginCount();
		if (retryCount > maxLoginCount) {
			throw new CommonException(USERNAME_OR_PWD_ERROR.getValue(), "您的密码错误次数已满，账号已被锁定，请10分钟在尝试。");
		}
	}
}
